package com.ucampus.controller;

import com.ucampus.entity.user;
import com.ucampus.entity.userinfo;
import com.ucampus.service.userLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能：
 * 作者： 启明星_Polaris
 * 日期：2024/12/27 上午9:47
 **/

@RestController
@RequestMapping("/user")
public class userLoginController {
    @Autowired
    private userLoginService userLoginService;
    @Autowired
    private com.ucampus.dao.userLoginMapper userLoginMapper;

    // 通过token值获取用户信息
    @GetMapping("/getUserByToken")
    public ResponseEntity<Map<String, Object>> getUserByToken(@RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();

        // 从 token 查询登录表，获取用户 ID
        user loginUser = userLoginMapper.findUserByToken(token);

        if (loginUser != null) {
            // 使用用户 ID 查询用户信息表
            userinfo userInfo = userLoginService.getUserInfoById(loginUser.getId());

            if (userInfo != null) {
                // 查询成功
                response.put("code", 200);
                response.put("message", "用户信息查询成功");
                response.put("user", userInfo); // 返回用户完整信息
                return ResponseEntity.ok(response);
            } else {
                // 用户信息表未找到
                response.put("code", 404);
                response.put("message", "未找到用户详细信息，请检查数据是否完整。");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } else {
            // 登录表中未找到用户
            response.put("code", 404);
            response.put("message", "无效的 token，请检查 token 是否正确。");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }


    // 登录接口
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestParam(required = false) Integer id,
                                       @RequestParam(required = false) String userPhone,
                                       @RequestParam(required = false) String userWX,
                                       @RequestParam(required = false) String userQQ,
                                       @RequestParam String userpassword){

        Map<String, Object> response = new HashMap<>();
        // 优先通过id登录
        if (id != null){
            // 检测账号是否被封禁
            user currentUser = userLoginMapper.findUserById(id);
            if (currentUser != null && !"可用".equalsIgnoreCase(currentUser.getStatus())) {
                response.put("code", 403);
                response.put("message", "账户已被封禁，请联系管理员。");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            // 检测账号是否和密码匹配
            if (userLoginService.loginById(id, userpassword)) {
                user loggedInUser = userLoginService.getUserByToken(userLoginMapper.findUserById(id).getToken());
                response.put("code", 200);
                response.put("message", "登录成功");
                response.put("token", loggedInUser.getToken());
                response.put("expiretime", loggedInUser.getExpiretime());
                return ResponseEntity.ok(response);

            }
        }


        // 通过手机号登录
        if (userPhone != null) {
            // 检测账号是否被封禁
            // 根据手机号查询用户
            long userId = userLoginMapper.getIdByPhone(userPhone);
            user currentUser = userLoginMapper.findUserById(userId);
            if (currentUser != null && !"可用".equalsIgnoreCase(currentUser.getStatus())) {
                response.put("code", 403);
                response.put("message", "账户已被封禁，请联系管理员。");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            if (userLoginService.loginByPhone(userPhone, userpassword)) {
                long userid = userLoginMapper.getIdByPhone(userPhone);
                user loggedInUser = userLoginMapper.findUserById(userid);
                response.put("code", 200);
                response.put("message", "手机号登录成功");
                response.put("token", loggedInUser.getToken());
                response.put("expiretime", loggedInUser.getExpiretime());
                return ResponseEntity.ok(response);
            }
        }
        // 通过微信号登录
        if (userWX != null) {
            // 检测账号是否被封禁
            // 根据微信号查询用户
            long userid = userLoginMapper.getIdByWX(userWX);
            user currentUser = userLoginMapper.findUserById(userid);
            if (currentUser != null && !"可用".equalsIgnoreCase(currentUser.getStatus())) {
                response.put("code", 403);
                response.put("message", "账户已被封禁，请联系管理员。");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            if( userLoginService.loginByWX(userWX, userpassword)) {
                long userId = userLoginMapper.getIdByWX(userWX);
                user loggedInUser = userLoginMapper.findUserById(userId);
                response.put("code", 200);
                response.put("message", "微信号登录成功");
                response.put("token", loggedInUser.getToken());
                response.put("expiretime", loggedInUser.getExpiretime());
                return ResponseEntity.ok(response);
            }
        }
        // 通过 QQ 号登录
        if (userQQ != null){
            // 检测账号是否被封禁
            // 根据 QQ 号查询用户
            long userId = userLoginMapper.getIdByQQ(userQQ);
            user currentUser = userLoginMapper.findUserById(userId);
            if (currentUser != null && !"可用".equalsIgnoreCase(currentUser.getStatus())) {
                response.put("code", 403);
                response.put("message", "账户已被封禁，请联系管理员。");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            if (userLoginService.loginByQQ(userQQ, userpassword)) {
                long userid = userLoginMapper.getIdByQQ(userQQ);
                user loggedInUser = userLoginMapper.findUserById(userid);
                response.put("code", 200);
                response.put("message", "QQ号登录成功");
                response.put("token", loggedInUser.getToken());
                response.put("expiretime", loggedInUser.getExpiretime());
                return ResponseEntity.ok(response);
            }
        }
        // 登录失败
        response.put("code", 401);
        response.put("message", "登录失败，请检查您的账号和密码是否匹配。");
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);

    }

    private boolean validatePassword(String inputPassword, String storedEncryptedPassword) {
        if (storedEncryptedPassword == null || storedEncryptedPassword.isEmpty()) {
            return false; // 如果数据库中没有存储密码，则直接返回false
        }

        // 1. 对用户输入的密码进行第一次MD5加密
        String firstMd5 = DigestUtils.md5DigestAsHex(inputPassword.getBytes());

        // 2. 获取用户输入密码的倒序
        String reversedPassword = new StringBuilder(inputPassword).reverse().toString();

        // 3. 拼接第一次MD5加密结果和倒序密码
        String combined = reversedPassword + firstMd5;

        // 4. 验证加密密码是否匹配
        return combined.equals(storedEncryptedPassword);
    }
}

